Skip to content

深入示例 (More on Examples)

在前面的指南中,我们讨论了如何为您的演示提供示例输入,以便用户更容易尝试。本章将深入探讨更多细节。

提供示例 (Providing Examples)

为 Interface 添加示例非常简单,只需要向 examples 关键字参数提供一个列表的列表。每个子列表是一个数据样本,其中每个元素对应于预测函数的一个输入。输入必须按照预测函数期望的顺序排列。

如果您的界面只有一个输入组件,那么您可以提供一个普通列表而不是列表的列表作为示例。

python
import gradio as gr

def calculator(num1, operation, num2):
    if operation == "add":
        return num1 + num2
    elif operation == "subtract":
        return num1 - num2
    elif operation == "multiply":
        return num1 * num2
    elif operation == "divide":
        if num2 == 0:
            raise gr.Error("不能除以零!")
        return num1 / num2

demo = gr.Interface(
    calculator,
    [
        "number",
        gr.Radio(["add", "subtract", "multiply", "divide"]),
        "number"
    ],
    "number",
    examples=[
        [45, "add", 3],
        [3.14, "divide", 2],
        [144, "multiply", 2.5],
        [0, "subtract", 1.2],
    ],
    title="简易计算器",
    description="这是一个简单的计算器演示。",
)

demo.launch()

从目录加载示例 (Loading Examples from a Directory)

您也可以指定包含示例的目录路径。如果您的 Interface 只接受单个文件类型输入,例如图像分类器,您可以简单地将目录文件路径传递给 examples= 参数,Interface 将加载目录中的图像作为示例。

在有多个输入的情况下,该目录必须包含一个 log.csv 文件,其中包含示例值。以计算器演示为例,我们可以设置 examples='/demo/calculator/examples',在该目录中包含以下 log.csv 文件:

csv
num,operation,num2
5,"add",3
4,"divide",2
5,"multiply",3

这在浏览已标记数据时很有帮助。只需指向已标记的目录,Interface 将从已标记的数据中加载示例。

提供部分示例 (Providing Partial Examples)

有时您的应用有许多输入组件,但您只想为其中一部分提供示例。为了从示例中排除某些输入,对于所有不需要提供示例的组件,在所有数据样本中传递 None

python
import gradio as gr

def greet(name, age, favorite_season):
    return f"你好 {name},你 {age} 岁了,你最喜欢的季节是 {favorite_season}!"

demo = gr.Interface(
    fn=greet,
    inputs=["text", "number", gr.Radio(["春", "夏", "秋", "冬"])],
    outputs=["text"],
    examples=[
        ["张三", None, None],   # 只为名字提供示例
        ["李四", 25, None],     # 为名字和年龄提供示例
        [None, None, "夏"],     # 只为季节提供示例
    ]
)

demo.launch()

缓存示例 (Caching Examples)

您可能希望为用户提供一些缓存的模型示例,以便他们可以快速尝试,特别是当您的模型通常需要一段时间才能运行时。如果设置 cache_examples=True,您的 Gradio 应用在调用 launch() 方法时会运行所有示例并保存输出结果。这些数据默认会保存在工作目录下名为 gradio_cached_examples 的目录中。您也可以通过 GRADIO_EXAMPLES_CACHE 环境变量设置此目录,可以是绝对路径或相对于工作目录的路径。

当用户点击一个示例时,输出将自动填充在应用中,使用来自缓存目录的数据,而不是实际运行函数。这很有用,让用户可以快速尝试您的模型而不增加任何负载!

或者,您可以设置 cache_examples="lazy"。这意味着每个特定示例只有在第一次被应用中的任何用户使用后才会被缓存。如果您的预测函数运行时间较长,并且您不希望在启动 Gradio 应用时等待很长时间,这很有帮助。

请记住,一旦生成缓存,它在未来的启动中不会自动更新。如果示例或函数逻辑发生变化,请删除缓存文件夹以清除缓存,并通过另一个 launch() 重建它。

python
import gradio as gr
import time

def slow_function(input_text):
    # 模拟一个耗时的处理过程
    time.sleep(3)
    return "处理完成:" + input_text

demo = gr.Interface(
    fn=slow_function,
    inputs="text",
    outputs="text",
    examples=["示例1", "示例2", "示例3"],
    cache_examples=True  # 启用缓存
)

demo.launch()

示例分页 (Examples Pagination)

当您加载大量数据集作为示例时,Gradio 会自动对示例进行分页显示。您可以通过 examples_per_page 参数配置每页显示的示例数量。

python
import gradio as gr

def echo(text):
    return text

demo = gr.Interface(
    fn=echo,
    inputs="text",
    outputs="text",
    examples=["示例" + str(i) for i in range(1, 21)],  # 20个示例
    examples_per_page=5  # 每页显示5个示例
)

demo.launch()

自定义示例标签 (Custom Example Labels)

如果您想为示例提供更友好或更描述性的标签,而不是直接显示示例值,可以使用 example_labels 参数。这个参数接受一个字符串列表,其长度应该与示例列表相同。

python
import gradio as gr

def image_classifier(img):
    # 模拟一个图像分类器
    return {"猫": 0.9, "狗": 0.1}

demo = gr.Interface(
    fn=image_classifier,
    inputs=gr.Image(),
    outputs=gr.Label(),
    examples=[
        "images/cat1.jpg",
        "images/cat2.jpg",
        "images/dog1.jpg"
    ],
    example_labels=[
        "橘色猫咪",
        "黑白猫咪",
        "棕色狗狗"
    ]
)

demo.launch()

结论

通过使用示例,您可以大大提高用户与您的 Gradio 应用程序的交互体验。无论是演示模型的功能,还是展示数据集中的有趣样本,示例都是让用户轻松上手的好方法。通过缓存示例,您甚至可以消除等待时间,使用户体验更加流畅。

在下一章中,我们将探讨如何使用 Flagging(标记)功能来收集用户反馈和数据。